<?php

class SQL {
	
	public $select 	= null;
	public $insert 	= null;
	public $update 	= null;
	public $delete 	= null;
 	public $from   	= null;
 	public $set   	= null;
 	public $inner  	= null;
 	public $left  	= null;
 	public $where  	= null;
	public $values 	= null;
 	public $or  	= null;
 	public $order  	= null;
	public $group  	= null;
	public $limit  	= null;
	
	public function Clear() {
		$this->select 	= null;
		$this->insert 	= null;
		$this->update 	= null;
		$this->delete 	= null;
 		$this->from   	= null;
 		$this->set   	= null;
 		$this->inner  	= null;
 		$this->left  	= null;
 		$this->where  	= null;
		$this->values 	= null;
 		$this->or  		= null;
 		$this->order  	= null;
		$this->group  	= null;
	}
	
	public function ToString() {
		
		$sql 	= 	"";
		
		$sql 	.= 	$this->BuildString($this->select, "SELECT %s", ", %s");
		$sql 	.= 	$this->BuildString($this->insert, "INSERT INTO %s", " (%s)");
		$sql 	.= 	$this->BuildString($this->update, "UPDATE %s", ", %s");
		$sql 	.= 	$this->BuildString($this->delete, "DELETE FROM %s", "");
		$sql 	.= 	$this->BuildString($this->from, " FROM %s", ", %s");
		$sql 	.= 	$this->BuildString($this->set, " SET %s", ", %s");
		$sql 	.= 	$this->BuildString($this->inner, " INNER JOIN %s", " INNER JOIN %s");
		$sql 	.= 	$this->BuildString($this->left, " LEFT JOIN %s", " LEFT JOIN %s");
		$sql 	.= 	$this->BuildString($this->where, " WHERE %s", " AND %s");
		$sql 	.= 	$this->BuildString($this->values, " VALUES (%s)", "");
		$sql 	.= 	$this->BuildString($this->or, " OR %s", " OR %s");
		$sql 	.= 	$this->BuildString($this->group, " GROUP BY %s", ", %s");
		$sql 	.= 	$this->BuildString($this->order, " ORDER BY %s", ", %s");
		$sql 	.= 	$this->BuildString($this->limit, " LIMIT %s", " %s");
												
		return $sql;
	}
	
	// ***********************************************************
	// Private Methods
	// ***********************************************************
	
	private function BuildString($item_array, $format1, $format2) {
		$s = "";
		if (!is_null($item_array)) {
			$isFirst = true;
			foreach ($item_array as $elt) {
				if ($isFirst) {
					$s .= sprintf($format1, $elt);
					$isFirst = false;
				} else {
					$s .= sprintf($format2, $elt);
				}
			}
		}
		return $s;
	} 
}

?>